package SceretKey;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.*;
import java.util.Base64;

/**
 * 生成国密加密算法的SM4和SM3密钥
 * @author xiexiaojin
 * @date 2025-07-17 15:51
 */
public class GenerateSMKey {
    private static final String TRANSFORMATION = "SM4/ECB/PKCS5Padding";  //ECB模式
    private static final String ALGORITHM = "SM4"; //加密算法

    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    public static void main(String[] args) throws Exception {
        // 生成SM3密钥对
        KeyPair keyPair = generateKeyPair();
        // 将密钥对转换为字符串
        String privateKeyStr = bytesToHex(keyPair.getPrivate().getEncoded());
        String publicKeyStr = bytesToHex(keyPair.getPublic().getEncoded());
        System.out.println("SM3私钥："+privateKeyStr);
        System.out.println("SM3公钥："+publicKeyStr);


        //生成SM4密钥
        System.out.println("SM4密钥（采用Base64编码）："+generateSM4Key());
    }
    public static KeyPair generateKeyPair() throws Exception {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", "BC");
        keyPairGenerator.initialize(512); // RSA密钥长度
        return keyPairGenerator.generateKeyPair();
    }

    /**
     *将字节数组转换为16进制字符串
     */
    public static String bytesToHex(byte[] bytes) {
        StringBuilder result = new StringBuilder();
        for (byte b : bytes) {
            result.append(String.format("%02X", b));
        }
        return result.toString();
    }

    // 生成SM4密钥
    public static String generateSM4Key() throws NoSuchAlgorithmException, NoSuchProviderException {
        KeyGenerator keyGen = KeyGenerator.getInstance(ALGORITHM, "BC");
        keyGen.init(128); // 初始化密钥长度为128位
        SecretKey secretKey = keyGen.generateKey();
        return Base64.getEncoder().encodeToString(secretKey.getEncoded());
    }

}
